package cn.shop.front.config.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 痴
 * @className redisConfig
 * @since 2020-03-30 14:14
 */
@Configuration
public class RedisConfig {

	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {

		RedisMessageListenerContainer container = new RedisMessageListenerContainer();
		container.setConnectionFactory(connectionFactory);
		return container;
	}

	/**
	 * 往容器中添加RedisTemplate对象，设置序列化方式
	 *
	 * @param redisConnectionFactory
	 * @return
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(valueSerializer());
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(valueSerializer());
		template.afterPropertiesSet();
		return template;

	}


	/**
	 * 使用Jackson序列化器
	 *
	 * @return
	 */
	private RedisSerializer<Object> valueSerializer() {
		Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		/**
		 * 这一句必须要，作用是序列化时将对象全类名一起保存下来
		 * 设置之后的序列化结果如下：
		 *  [
		 *   "com.dxy.cache.pojo.Dept",
		 *   {
		 *     "pid": 1,
		 *     "code": "11",
		 *     "name": "财务部1"
		 *   }
		 * ]
		 *
		 * 不设置的话，序列化结果如下，将无法反序列化
		 *
		 *  {
		 *     "pid": 1,
		 *     "code": "11",
		 *     "name": "财务部1"
		 *   }
		 */
		//                objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		//因为上面那句代码已经被标记成作废，因此用下面这个方法代替，仅仅测试了一下，不知道是否完全正确
		objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
		serializer.setObjectMapper(objectMapper);
		return serializer;
	}

}
